package com.liuhuan.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.liuhuan.service.SendMailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @version 1.0
 * @Author liuhuan
 * @Date 2024/7/6 16:56
 * @注释
 */

@Service
@Slf4j
public class SendMailServiceImpl implements SendMailService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String sendMailer;

    //检查邮件合法性
    public void checkMail(String email) {

    }

    @Override
    public String sendMail(String email) throws MessagingException {
        // 生成随机验证码
        String verifyCode = RandomUtil.randomNumbers(6);
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        checkMail(email);

        try {
            //邮件主题
            helper.setSubject("AI基础平台 - 用户认证");
            //邮件内容，设置为true表示支持HTML
            helper.setText(String.format("您的动态验证码为：<strong style='color: red'>%s</strong>，%d分钟内有效，若非本人操作，请勿泄露。", verifyCode, 5), true);
            //邮件发件人
            helper.setFrom(sendMailer);
            //邮件收件人
            helper.setTo(email);
            //邮件发送时间
            helper.setSentDate(new Date());

            javaMailSender.send(message);
            log.info("发送邮件成功:{}->{}");
        } catch (Exception e) {
            log.error("发送邮件失败", e);
        }
       return verifyCode;
    }


}


